import { Pagination } from 'antd';
import { FunctionComponent, useEffect, useState } from 'react';
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
interface ListPaginationProps {
  total: number;
}

const ListPagination: FunctionComponent<ListPaginationProps> = (
  props: ListPaginationProps,
) => {
  const [searchParams] = useSearchParams();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const nav = useNavigate();
  const { pathname } = useLocation();
  //page与pageSize改变，改变地址
  const hanlderPagination = (page: number, pageSize: number) => {
    // const originalParmas = Object.fromEntries(searchParams.entries());
    // const newParams = {
    //   ...originalParmas,
    //   page: page.toString(),
    //   pageSize: pageSize.toString(),
    // };
    // setSearchParams(newParams);
    console.log(searchParams.toString());
    searchParams.set('page', page.toString());
    searchParams.set('pageSize', pageSize.toString());
    nav({
      pathname: pathname,
      search: searchParams.toString(),
    });
    setCurrent(page);
  };
  useEffect(() => {
    const page = Number(searchParams.get('page') || 1);
    setCurrent(page);
    const pageSize = Number(searchParams.get('pageSize') || 10);
    setPageSize(pageSize);
  }, [searchParams.get('page'), searchParams.get('pageSize')]);
  return (
    <div>
      <Pagination
        current={current}
        total={props.total}
        pageSize={pageSize}
        onChange={hanlderPagination}
      />
    </div>
  );
};

export default ListPagination;
